package org.lboot.flow.processor.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.flow.constant.FlowNodeTypeConst;
import org.lboot.flow.event.system.FlowProcessEvent;
import org.lboot.flow.event.system.FlowStartEvent;
import org.lboot.flow.model.node.BaseModel;
import org.lboot.flow.module.work.FlowWork;
import org.lboot.flow.module.work.FlowWorkService;
import org.lboot.flow.module.work.params.FlowTaskParams;
import org.lboot.flow.processor.FlowNodeProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
@AllArgsConstructor
public class StartNodeProcessorImpl implements FlowNodeProcessor {

    FlowWorkService flowWorkService;

    @Resource
    ApplicationContext context;

    @Override
    public String getNodeType() {
        return FlowNodeTypeConst.START_NODE;
    }

    @SneakyThrows
    @Override
    public void process(FlowWork flowWork, FlowTaskParams taskParams) {
        FlowWork oldFlow = new FlowWork();
        BeanUtil.copyProperties(flowWork,oldFlow, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        // 流程启动事件发布
        context.publishEvent(new FlowStartEvent(this,flowWork));
        // 流程执行到下一步
        BaseModel nextNode = flowWork.getNextModel();
        flowWork.setCurrentNodeId(nextNode.getId());
        flowWork.setCurrentNodeType(nextNode.getNodeType());
        flowWork.setNextNodeId(nextNode.getNextNodeId());
        flowWorkService.updateOne(flowWork);
        // 发布流程节点流程流转事件
        context.publishEvent(new FlowProcessEvent(this,oldFlow,flowWork,taskParams));
    }

    @Override
    public void back(FlowWork flowWork, FlowTaskParams params) {
        // do nothing
    }
}
